#include "mainwindow.h"

#include <QDockWidget>
#include <QVBoxLayout>
#include "setdlg.h"
#include "measure.h"
#include <QTableWidgetItem>
#include <QIcon>
#include <QLabel>
#include <QPixmap>
#include "winsock2.h"

#include <QSpacerItem>
#ifdef __CURVE__
#include "dlgcurve.h"
#endif
//#include "shapeitem.h"

QTextEdit *logText;
typedef bool*(*exported_proc_logini)(std::string);
typedef bool*(*exported_proc_log)(std::string);
exported_proc_logini LogIni;
exported_proc_log ShowLog;


//#define setlocale libintl_setlocale
//extern char *setlocale (int, const char *);
typedef char *(*Lib_intl_setlocale)(int,const char *);
//libintl_bindtextdomain
typedef char *(*Lib_intl_bindtextdomain)(const char *,const char *);
//libintl_textdomain
typedef char *(*Lib_intl_textdomain)(const char *);

Lib_intl_setlocale intl_setlocale;
Lib_intl_bindtextdomain intl_bindtextdomain;
Lib_intl_textdomain intl_textdomain;

//extern XDOGNEW_EXPORTS  int int_DogInitial_software(std::string& statusInfo, int& year, int& mounth, int& day);
typedef int (*int_DogInitial_software)(std::string& statusInfo, int& year, int& mounth, int& day);
typedef bool (*DogInitial_software)();

int_DogInitial_software DogInt;
DogInitial_software  Dog_software;

fsTcpSocket::fsTcpSocket(QObject* parent):
    QTcpSocket(parent)
{

}
fsTcpSocket::~fsTcpSocket()
{

}

void fsTcpSocket::SetLocalPort(QString ip,quint16 port)
{
    QAbstractSocket::setLocalPort(port);
    //QHostAddress address = QHostAddress(ip);
    //quint32 ip4Add = address.toIPv4Address();
    bind(QHostAddress::Any,port);//QAbstractSocket::ReuseAddressHint | QAbstractSocket::ShareAddress|QAbstractSocket::DontShareAddress );
}

int dog(){
    int ret = 0;
    bool bret = false;
    QLibrary mydog("XDogNew");
    if(mydog.load()){
         qDebug() << "doghook success.";
         std::string statusInfo;
         int year, mounth, day;
         DogInt = (int_DogInitial_software)mydog.resolve("?int_DogInitial_software@@YAHAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@AEAH11@Z");
         Dog_software = (DogInitial_software)mydog.resolve("?DogInitial_software@@YA_NXZ");

         if(Dog_software){
             //ret = DogInt(statusInfo,year,mounth,day);
             bret = Dog_software();
             if(bret == true ){
                //qDebug() << statusInfo.c_str() << year << mounth <<day;
                qDebug() << "dog OK";
                ret = 1;
             }
             else{
                 qDebug() << "dog Failed.";
             }
         }
         else{
             qDebug() << "DogInt Failed.";
         }
    }
    else{
        qDebug() << "doghook failed.";
    }

    //ret = 1;
    return  ret;
}


void MainWindow::test()
{
    QLibrary mylib("log");
    std::string pt;
    QDir dir = QDir::temp();
    dir.cdUp();
    dir.cdUp();
    QString strDir = dir.absolutePath();



    strDir.append("/Roaming/fsapp");
    if(dir.exists(strDir))
        pt = strDir.toStdString();
    else{
        strDir = QDir::currentPath();
        pt =strDir.toStdString();
    }

    if(mylib.load())
    {
        qDebug() << "dllhook加载成功:";
        LogIni = (exported_proc_logini)mylib.resolve("Ini");
        ShowLog = (exported_proc_log)mylib.resolve("ShowLog");
        if(LogIni){
            LogIni(pt);
            ShowLog("dllhook加载成功:");
        }

        //SetKeyBoardHook open = (SetKeyBoardHook)mylib.resolve("SetKeyBoardHook");
        //if(open)
        //{
         //   qDebug() << "SetKeyBoardHook加载成功";
         //   bool flag = open((HWND)this->winId());
        //}

    }



    QLibrary myText("libintl3");
    if(myText.load())
    {
        qDebug() << "GNU.Gettext加载成功:";
        intl_setlocale = (Lib_intl_setlocale)mylib.resolve("libintl_setlocale");
        //intl_setlocale = (Lib_intl_setlocale)mylib.resolve("libintl_setlocale");
        intl_bindtextdomain = (Lib_intl_bindtextdomain)mylib.resolve("libintl_bindtextdomain");
        intl_textdomain = (Lib_intl_textdomain)mylib.resolve("libintl_textdomain");
        //setlocale( LC_ALL, "" );
        intl_setlocale( LC_ALL, "" );
        intl_bindtextdomain( "fsapp", "./" );
        intl_textdomain( "fsapp" );
    }

}
void MainWindow::dogonOutput()
{
    QByteArray qbt = m_Process->readAllStandardOutput();
    QString msg = QString::fromLocal8Bit(qbt);
    QStringList list1 = msg.split("\r\n");
    foreach(QString v , list1)
    {
        qDebug() << v;
    }


}
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      m_SqLPara(nullptr),
      m_RunTable(nullptr),
      m_TcpRobot(nullptr),
      m_TcpCamera(nullptr),
      m_Process(new QProcess),
      m_MisConReplayCnt(-1)
{
    //setWindowTitle(tr("DockWidget"));
    setWindowTitle(_("Car"));
    resize(800,600);
    //QTextEdit *text = new QTextEdit(this);
    //text->setText(tr("主窗口"));
    //text->setAlignment(Qt::AlignCenter);
    //setCentralWidget(text);
    test();
    qInstallMessageHandler(logOutput);

    logText = new QTextEdit();
    logText->setReadOnly(true);
    QWidget* p = takeCentralWidget();
    if(p)
        delete p;
    m_Process->setProcessChannelMode(QProcess::MergedChannels);
    connect(m_Process,SIGNAL(readyReadStandardOutput()),this,SLOT(dogonOutput()));
    qDebug() <<"222222";
    QString ss = _("test_test");
    qDebug() << ss ;



    qDebug() <<"1111111111";

    //m_Process->start("XDogNew.exe");
    //if(dog()!=1)
    //{
        //QMessageBox box(QMessageBox::Critical,"错误！","加密狗错误，请确认加密狗已插入或联系厂家解决。");
        //box.setStandardButtons (QMessageBox::Ok|QMessageBox::Cancel);
        //box.setStandardButtons (QMessageBox::Ok);
        //box.setButtonText (QMessageBox::Ok,QString("确 定"));
        //box.setButtonText (QMessageBox::Cancel,QString("取 消"));
        //box.exec();
        //MSGINF::MsgShowOk(this,_("Critical"),_("Dongle error, please confirm that the dongle is inserted or contact the manufacturer to resolve it"));
        //exit(0);
    //}
    //m_Process->terminate();

    setDockNestingEnabled(true);

    setWindowIcon(QIcon("://images/fsapp.ico"));

    m_SqLPara = new CSql();

    dock1 = new QDockWidget(_("Project:none"),this);
    //dock->setFeatures(QDockWidget::DockWidgetMovable); //指定停靠窗体的样式，此处为可移动
    dock1->setFeatures(QDockWidget::NoDockWidgetFeatures); //没有相关的权限    dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::TopDockWidgetArea | Qt::BottomDockWidgetArea);
    //dock1->setAllowedAreas(Qt::TopDockWidgetArea);
    //dock1->setAllowedAreas(Qt::LeftDockWidgetArea);
    //dock1->setMaximumSize(this->geometry().height(),this->geometry().width());

    //QTextEdit *text1 = new QTextEdit();

    //car type
    QHBoxLayout *layoutMode = new QHBoxLayout;
    QLabel *lb = new QLabel(_("CarType")+":");
    m_ModeTxt = new QLineEdit();
    m_ModeTxt->setMaxLength(20);
    m_ModeTxt->setText(tr(""));
    //m_ModeTxt->setMaximumHeight(20);
    //m_ModeTxt->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    layoutMode->addWidget(lb);
    layoutMode->addWidget(m_ModeTxt);


    MyWidget *wi = new MyWidget;

    CreateToolBar();

    m_RunTable = new QTableWidget(dock1);
    m_RunTable->setSelectionMode(QAbstractItemView::SingleSelection);

    connect(m_RunTable,SIGNAL(cellChanged(int,int)),this,SLOT(RuncellChanged(int,int)));
    connect(m_RunTable,SIGNAL(itemChanged(QTableWidgetItem*)),this,SLOT(RunitemChanged(QTableWidgetItem*)));
    connect(m_RunTable,SIGNAL(itemSelectionChanged()),this,SLOT(RunitemSelectionChanged()));

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(toolBar);
    //layout->addWidget(m_ModeTxt);
    layout->addLayout(layoutMode);
    layout->addWidget(m_RunTable);
    layout->setContentsMargins(0, 0, 0, 0);
    wi->setLayout(layout);
    dock1->setWidget(wi);

    //dock1->setWidget(text1);
    addDockWidget(Qt::LeftDockWidgetArea,dock1);
    //
#ifdef __CURVE__
    QDockWidget *dock222 = new QDockWidget(tr("Curve"),this);
    dock222->setFeatures(QDockWidget::NoDockWidgetFeatures); //没有相关的权限
    //

    QVBoxLayout *clayout = new QVBoxLayout;
    QWidget *paintArea = new QWidget;
    myPlot = new QCustomPlot(paintArea);
    DlgCurve* dd = new DlgCurve(this,m_SqLPara,myPlot);

    clayout->addWidget(dd);
    clayout->addWidget(myPlot,0,Qt::AlignHCenter);

    //为水平布局左侧，添加固定长度120大小的弹簧
    QSpacerItem *m_VSpacer = new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Expanding);
    clayout->addItem(m_VSpacer);

    //clayout->addSpacing(1024);
    clayout->setContentsMargins(0, 0, 0, 0);
    paintArea->setLayout(clayout);
    dock222->setWidget(paintArea);
#endif
    //

    dock2 = new QDockWidget(_("Prject:none Layer:none"),this);
    dock2->setFeatures(QDockWidget::NoDockWidgetFeatures); //没有相关的权限
    //dock2->setAllowedAreas(Qt::RightDockWidgetArea);

    QTextEdit *text2 = new QTextEdit();
    text2->setText(tr("窗口二"));
    //dock2->setWidget(text2);
    //

    m_box = new SortingBox(dock2,m_SqLPara);

    connect(this,SIGNAL(myRunSignal(bool)),m_box,SLOT(myRunning(bool)));
    connect(this,SIGNAL(boxShowPin(QString ,QString)),m_box,SLOT(OnboxShowPin(QString ,QString)));
    connect(this,SIGNAL(showGapFlush(QString ,QString,QString,int)),m_box,SLOT(OnShowGapFlush(QString ,QString,QString,int)));
    connect(m_box,SIGNAL(ClearRunTable()),this,SLOT(OnClearRunTable()));
    connect(m_box,SIGNAL(ShowHideDock1(bool)),this,SLOT(OnShowHideDock1(bool)));

    dock2->setWidget(m_box);
    //addDockWidget(Qt::RightDockWidgetArea,dock2);
    //
    QDockWidget *dock3 = new QDockWidget(tr("日志"),this);
    //dock3->setFeatures(QDockWidget::AllDockWidgetFeatures); //具有全部特性
    dock3->setFeatures(QDockWidget::NoDockWidgetFeatures); //没有相关的权限
    //dock3->setAllowedAreas(Qt::RightDockWidgetArea);


    logText->setText(tr("窗口三"));
    dock3->setWidget(logText);
    //addDockWidget(Qt::RightDockWidgetArea,dock3);


    splitDockWidget(dock1,dock2,Qt::Horizontal);
    splitDockWidget(dock2,dock3,Qt::Vertical);

    //tabifyDockWidget(dock1,dock2);
    #ifdef __CURVE__
    tabifyDockWidget(dock2,dock222);
    #endif
    dock2->raise();

    QList<QDockWidget*> temp_docklist;
    QList<int> temp_sizelist;

    temp_docklist << dock1;
    temp_docklist << dock2;
    //temp_docklist << dock3;
    temp_sizelist << static_cast<int>(this->geometry().width() * 0.3);
    temp_sizelist << static_cast<int>(this->geometry().width() * 0.7);
    //temp_sizelist << static_cast<int>(this->geometry().width() * 0.9);
    this->resizeDocks(temp_docklist, temp_sizelist, Qt::Horizontal);



    temp_docklist.clear();
    temp_sizelist.clear();

    //temp_docklist << dock1;
    temp_docklist << dock2;
    temp_docklist << dock3;

    //temp_sizelist<< static_cast<int>(this->geometry().width() * 0.25);
    temp_sizelist<< static_cast<int>(this->geometry().height() * 0.8);
    temp_sizelist<< static_cast<int>(this->geometry().height() * 0.2);
    this->resizeDocks(temp_docklist, temp_sizelist, Qt::Vertical);

    //dock3->hide();

    //
    m_TcpRobot = new fsTcpSocket();
    m_TcpRobot->setObjectName("TcpRobot");
    connect(m_TcpRobot, SIGNAL(error(QAbstractSocket::SocketError)),
    this, SLOT(displayError(QAbstractSocket::SocketError)));
    connect(m_TcpRobot, SIGNAL(readyRead()), this, SLOT(onReadyReadRobot()));
    connect(m_TcpRobot, SIGNAL(disconnected()), this, SLOT(onDisconnectRobot()));
    connect(m_TcpRobot, SIGNAL(connected()), this, SLOT(onConnectRobot()));
    //connect(m_TcpRobot, &QTcpSocket::readyRead, this, [=]()
    //    {
    //     qDebug() << "received:" << m_TcpRobot->readAll();
    //     //m_TcpRobot->close();
    //    });

    m_TcpCamera = new fsTcpSocket();
    m_TcpCamera->setObjectName("TcpCamera");
    connect(m_TcpCamera, SIGNAL(error(QAbstractSocket::SocketError)),
    this, SLOT(displayError(QAbstractSocket::SocketError)));
    connect(m_TcpCamera, SIGNAL(readyRead()), this, SLOT(onReadyReadCamera()));
    connect(m_TcpCamera, SIGNAL(disconnected()), this, SLOT(onDisconnectCamera()));
    connect(m_TcpCamera, SIGNAL(connected()), this, SLOT(onConnectCamera()));

    m_TcpMIS = new fsTcpSocket();
    m_TcpMIS->setObjectName("m_TcpMIS");
    connect(m_TcpMIS, SIGNAL(error(QAbstractSocket::SocketError)),
    this, SLOT(displayError(QAbstractSocket::SocketError)));
    connect(m_TcpMIS, SIGNAL(readyRead()), this, SLOT(onReadyReadMIS()));
    connect(m_TcpMIS, SIGNAL(disconnected()), this, SLOT(onDisconnectMIS()));
    connect(m_TcpMIS, SIGNAL(connected()), this, SLOT(onConnectMIS()));

    int enable = 1;
    setsockopt(m_TcpRobot->socketDescriptor(), SOL_SOCKET, SO_REUSEADDR,  (char*)&enable, sizeof(int));
    setsockopt(m_TcpCamera->socketDescriptor(), SOL_SOCKET, SO_REUSEADDR,  (char*)&enable, sizeof(int));
    setsockopt(m_TcpMIS->socketDescriptor(), SOL_SOCKET, SO_REUSEADDR,  (char*)&enable, sizeof(int));




    dock3->hide();

     RECORDSET tmp;
    tmp = m_SqLPara->RecordSet("select * from SetUp");
    qDebug()<< tmp.size();
    logText->setText(QString("%1").arg(tmp.size()));

}
void MainWindow::myRunning()
{
    //bool checked = ((QToolButton*)sender())->isChecked();
    bool checked = ((QAction*)sender())->isChecked();
    qDebug()<<"from "<< checked;
    m_clsid = m_ModeTxt->text();
    m_clsid = m_clsid.trimmed();

    if(m_RunTable->rowCount()<=0 || m_clsid == ""){
        QMessageBox box(QMessageBox::Warning,_("Warning"),_("Project Or CarType Is None,Select Open Project Or Input CarType Please!"));
        //box.setStandardButtons (QMessageBox::Ok|QMessageBox::Cancel);
        box.setStandardButtons (QMessageBox::Ok);
        box.setButtonText (QMessageBox::Ok,QString(_("Ok")));
        box.setButtonText (QMessageBox::Cancel,QString("Cancel"));
        box.exec();

        //((QToolButton*)sender())->setChecked(false);
        m_RunAct->setChecked(false);
        m_OpenSolutionAct->setEnabled(true);
        m_MeasureAct->setEnabled(true);
        m_SettingAct->setEnabled(true);
        return;
    }


    //m_RunTable->setCurrentItem(NULL);
    //m_RunTable->setSelectionMode(QAbstractItemView::NoSelection);
    m_box->RefresItem();
    //emit this->myRunSignal(((QToolButton*)sender())->isChecked());
    emit this->myRunSignal(checked);


    m_OpenSolutionAct->setEnabled(!checked);
    m_MeasureAct->setEnabled(!checked);
    m_SettingAct->setEnabled(!checked);
    //ActToolbar[0]->setEnabled(!checked);
    //ActToolbar[1]->setEnabled(!checked);
    //ActToolbar[2]->setEnabled(!checked);
    //

    std::string str,IP1 = "",IP2,IP3,Port1,Port2,Port3,Port4,Port5,chkstart;
    str = "select * from SetUp;";
    m_SqLPara->exeSql("select * from SetUp");

    m_SqLPara->GetValue("LocalIP",IP1);
    m_SqLPara->GetValue("RemoteIP",IP2);
    m_SqLPara->GetValue("LocalPort",Port1);
    m_SqLPara->GetValue("LocalPort1",Port2);
    m_SqLPara->GetValue("RemotePort",Port3);
    m_SqLPara->GetValue("BackPort",Port4);
    m_SqLPara->GetValue("MIS-IP",IP3);
    m_SqLPara->GetValue("MIS-Port",Port5);
    m_SqLPara->GetValue("MIS-Start",chkstart);


    qDebug() << IP1.c_str()<< IP2.c_str() << Port1.c_str() << Port2.c_str() << Port3.c_str() << Port4.c_str()  ;


    int iPort1,iPort2,iPort3,iPort4,iPort5;
    iPort1 = QString(Port1.c_str()).toULong();
    iPort2 = QString(Port2.c_str()).toULong();
    iPort3 = QString(Port3.c_str()).toULong();
    iPort4 = QString(Port4.c_str()).toULong();
    iPort5 = QString(Port5.c_str()).toULong();

    if(checked){
        ;
    }
    else{
        //if(m_TcpCamera != nullptr){
            if(m_TcpRobot->state() == QAbstractSocket::ConnectedState)
            {
                m_TcpRobot->disconnectFromHost();
                if (m_TcpRobot->waitForDisconnected(3000)) {
                          qDebug("Disconnected!");
                  }
                m_TcpRobot->abort();
                m_TcpRobot->close();
            }



            //delete m_TcpRobot;
        //}
        //if(m_TcpCamera != nullptr){
            if(m_TcpCamera->state() == QAbstractSocket::ConnectedState)
            {
                m_TcpCamera->disconnectFromHost();
                if (m_TcpCamera->waitForDisconnected(3000)) {
                          qDebug("Disconnected!");
                  }
                m_TcpCamera->abort();
                m_TcpCamera->close();
            }

            if(m_TcpMIS->state() == QAbstractSocket::ConnectedState)
            {
                m_TcpMIS->disconnectFromHost();
                if (m_TcpMIS->waitForDisconnected(3000)) {
                          qDebug("Disconnected!");
                  }
                m_TcpMIS->abort();
                m_TcpMIS->close();
            }

            //delete m_TcpCamera;
        //}
        return;
    }
    BOOL  bDontLinger = FALSE;
    m_TcpRobot->SetLocalPort(QString(IP1.c_str()),(quint16)iPort2);
    if(iPort4>0){
        //m_TcpRobot->SetLocalPort(QString(IP2.c_str()),(quint16)iPort2);
        m_TcpRobot->connectToHost(QString(IP2.c_str()),(quint16)iPort4,QAbstractSocket::ReadWrite,QAbstractSocket::IPv4Protocol);
    }
    else
        m_TcpRobot->connectToHost(QString(IP2.c_str()),(quint16)iPort3,QAbstractSocket::ReadWrite,QAbstractSocket::IPv4Protocol);

    if(!m_TcpRobot->waitForConnected(5000))
    {
      qDebug() << "Error: " << m_TcpRobot->errorString();
      //((QToolButton*)sender())->setChecked(false);
      goto TCPERROR;
    }
    m_TcpCamera->SetLocalPort(QString(IP1.c_str()),(quint16)iPort1);
    m_TcpCamera->connectToHost(QString(IP2.c_str()),(quint16)iPort3,QAbstractSocket::ReadWrite,QAbstractSocket::IPv4Protocol);
    if(!m_TcpCamera->waitForConnected(5000))
    {
      qDebug() << "Error: " << m_TcpCamera->errorString();
      //((QToolButton*)sender())->setChecked(false);
      goto TCPERROR;
    }


    setsockopt(m_TcpRobot->socketDescriptor(),SOL_SOCKET,SO_DONTLINGER,(const char*)&bDontLinger,sizeof(BOOL));
    setsockopt(m_TcpCamera->socketDescriptor(),SOL_SOCKET,SO_DONTLINGER,(const char*)&bDontLinger,sizeof(BOOL));

    if(chkstart=="1"){
        m_TcpMIS->SetLocalPort(QString(IP1.c_str()),(quint16)8989);
        m_TcpMIS->connectToHost(QString(IP3.c_str()),(quint16)iPort5,QAbstractSocket::ReadWrite,QAbstractSocket::IPv4Protocol);
        if(!m_TcpMIS->waitForConnected(5000))
        {
          qDebug() << "Error: " << m_TcpMIS->errorString();
          //((QToolButton*)sender())->setChecked(false);
          goto TCPERROR;
        }
        setsockopt(m_TcpMIS->socketDescriptor(),SOL_SOCKET,SO_DONTLINGER,(const char*)&bDontLinger,sizeof(BOOL));

        m_MisConReplayCnt = 3;
    }

return;

TCPERROR:
    MSGINF::MsgShowOk(this,_("Warning"),_("Tcp Connect Error.Please Review Net Config."));
    m_TcpRobot->abort();
    m_TcpCamera->abort();
    m_TcpMIS->abort();
    m_TcpRobot->close();
    m_TcpCamera->close();
    m_TcpMIS->close();
    m_RunAct->setChecked(false);
    m_OpenSolutionAct->setEnabled(true);
    m_MeasureAct->setEnabled(true);
    m_SettingAct->setEnabled(true);
    m_MisConReplayCnt = -1;
    emit this->myRunSignal(false);
    return;
}
void MainWindow::mySetting()
{
    qDebug()<<"mySetting ";
    SetDlg* dlg = new SetDlg(this,m_SqLPara);
    Qt::WindowFlags flags = Qt::Dialog;
    flags |= Qt::WindowCloseButtonHint;
    dlg->setWindowFlags(flags);
    dlg->setFixedSize(429,169);
    dlg->exec();

}
void MainWindow::myPointS()
{
    qDebug()<<"myPointS ";
    Measure* dlg = new Measure(m_SqLPara,this);
    Qt::WindowFlags flags = Qt::Dialog;
    flags |= Qt::WindowCloseButtonHint;
    dlg->setWindowFlags(flags);
    dlg->setFixedSize(666,458);
    dlg->exec();

    m_box->RefresItem();

}


MainWindow::~MainWindow()
{
    delete m_SqLPara;

    //m_TcpRobot->disconnectFromHost();
    m_TcpRobot->close();
    m_TcpRobot->abort();

    //m_TcpCamera->disconnectFromHost();
    m_TcpCamera->close();
    m_TcpRobot->abort();

}


void MainWindow::write(QString str)
{
    //text = str;
    if(logText->toPlainText().length()>4000)
        logText->clear();
    logText->append(str);
    logText->moveCursor(QTextCursor::End);
    ShowLog(str.toStdString());
}

void MainWindow::logOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString text;
    QString file =context.file;
    QString func =context.function;
    int pos = file.lastIndexOf("\\");
    file = file.mid(pos+1);
    pos = func.indexOf("(");
    func = func.mid(0,pos);
    QString tmp = QString("[%1][%2][%3]").arg(file).arg(func).arg(context.line);
    text.append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") + " "+ tmp);
    switch(type)
    {
        case QtDebugMsg:
            text.append("Debug:");
            break;

        case QtWarningMsg:
            text.append("Warning:");
            break;

        case QtCriticalMsg:
            text.append("Critical:");
            break;

        case QtFatalMsg:
            text.append("Fatal:");
    }

    text.append(msg);
    write(text);
}
void MainWindow::CreateMainBar()
{
    QMenuBar *bar = this->menuBar();
    QMenu *oper = new QMenu(_("Oper"));
    QMenu *help = new QMenu(_("help"));

    m_RunAct = new QAction(QIcon(":/images/Find.png"),_("Run"));
    m_RunAct->setEnabled(true);
    m_RunAct->setCheckable(true);
    connect(m_RunAct,SIGNAL(triggered()),this,SLOT(myRunning()));

    m_OpenSolutionAct = new QAction(QIcon(":/images/Create.png"),_("OpenSolution"));
    connect(m_OpenSolutionAct,SIGNAL(triggered()),this,SLOT(showRunTable()));

    m_MeasureAct = new QAction(QIcon(":/images/Pin.png"),_("SolutionSet"));
    connect(m_MeasureAct,SIGNAL(triggered()),this,SLOT(myPointS()));

    m_SettingAct = new QAction(QIcon(":/images/Settings.png"),_("SystemSet"));
    connect(m_SettingAct,SIGNAL(triggered()),this,SLOT(mySetting()));

    m_helpAct = new QAction(_("Help"));
    connect(m_helpAct,SIGNAL(triggered()),this,SLOT(myHelp()));
    m_aboutAct = new QAction(_("About"));
    connect(m_aboutAct,SIGNAL(triggered()),this,SLOT(myAbout()));

    m_exportAct = new QAction(_("ExportData"));
    connect(m_exportAct,SIGNAL(triggered()),this,SLOT(myExport()));
    m_importAct = new QAction(_("ImportData"));
    connect(m_importAct,SIGNAL(triggered()),this,SLOT(myImport()));

    oper->addAction(m_RunAct);
    oper->addAction(m_OpenSolutionAct);
    oper->addAction(m_MeasureAct);
    oper->addAction(m_SettingAct);
    oper->addAction(m_exportAct);
    oper->addAction(m_importAct);

    help->addAction(m_helpAct);
    help->addAction(m_aboutAct);

    bar->addMenu(oper);
    bar->addMenu(help);




}

void MainWindow::CreateToolBar()
{
    toolBar = new QToolBar;
    toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    toolBar->setIconSize(QSize(32,32));
    CreateMainBar();

    toolBar->addAction(m_RunAct);
    toolBar->addAction(m_OpenSolutionAct);
    toolBar->addAction(m_MeasureAct);
    toolBar->addAction(m_SettingAct);

/*
    QToolButton *newRunButton = new QToolButton(toolBar);
    newRunButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    newRunButton->setToolTip(_("Run"));
    newRunButton->setText(_("Run"));
    newRunButton->setIcon(QIcon(":/images/Find.png"));
    newRunButton->setIconSize(QSize(32, 32));
    newRunButton->setCheckable(true);
    //newRunButton->setChecked(true);
    connect(newRunButton, SIGNAL(clicked()), this, SLOT(myRunning()));
    //connect(this,SIGNAL(myRunSignal(bool)),this,SLOT(myRunning(bool)));
    toolBar->addWidget(newRunButton);

    QToolButton *newCreateS = new QToolButton(this);
    newCreateS->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    newCreateS->setToolTip("OpenSolution");
    newCreateS->setText(_("OpenSolution"));
    newCreateS->setIcon(QIcon("://images/Create.png"));
    newCreateS->setIconSize(QSize(32, 32));
    connect(newCreateS, SIGNAL(clicked()), this, SLOT(showRunTable()));
    ActToolbar[0] =  toolBar->addWidget(newCreateS);


    QToolButton *PointS = new QToolButton(this);
    PointS->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    PointS->setToolTip(_("SolutionSet"));
    PointS->setText(_("OpenSolution"));
    PointS->setIcon(QIcon("://images/Pin.png"));
    PointS->setIconSize(QSize(32, 32));
    connect(PointS, SIGNAL(clicked()), this, SLOT(myPointS()));
    ActToolbar[1] = toolBar->addWidget(PointS);


    QToolButton *Setting = new QToolButton(this);
    Setting->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    Setting->setToolTip(_("SystemSet"));
    Setting->setText(_("SystemSet"));
    Setting->setIcon(QIcon("://images/Settings.png"));
    Setting->setIconSize(QSize(32, 32));
    connect(Setting, SIGNAL(clicked()), this, SLOT(mySetting()));
    ActToolbar[2] = toolBar->addWidget(Setting);
*/
}

void MainWindow::showRunTable()
{
    QStringList headL;
    //headL << "Label"<<"GapNom"<<"Gap+"<<"Gap-"<<"FlushNum"<<"Gap"<<"FLush"<<"ICON";

    bool ok = false;
    QString sql;
    QStringList items,layers;
    NODE nd;
    NODE rds;
    std::string value,vlayer;;
    items << tr("Spring") << tr("Summer") << tr("Fall") << tr("Winter");
    items.clear();
    layers.clear();

    RECORDSET rd = m_SqLPara->RecordSet("select * from fsapp");

    if(rd.size()>0){
        for(RECORDSET::iterator it = rd.begin();it!=rd.end();it++){
        //for(int i = 0;i<rd.size();i++){
            nd =  *it;
            value = nd["value"];
            items << QString::fromLocal8Bit(value.c_str());
        }
    }
    else{
        QMessageBox box(QMessageBox::Warning,_("Warning"),_("Project Is None,Create Project Please！"));
        //box.setStandardButtons (QMessageBox::Ok|QMessageBox::Cancel);
        box.setWindowFlags(Qt::Dialog|Qt::WindowCloseButtonHint);
        box.setStandardButtons (QMessageBox::Ok);
        box.setButtonText (QMessageBox::Ok,QString(_("Ok")));
        box.setButtonText (QMessageBox::Cancel,QString(_("Cancel")));
        box.exec();
        return;
    }
//    QString item = QInputDialog::getItem(this, tr("打开工程"),
//                                         tr("请选择要打开的工程:"), items, 0, false, &ok);
    QString item = MSGINF::MsgGetItem(this,_("Open Project"),_("Select Open Project Please!"),items,&ok);

    if (ok && !item.isEmpty()){

        sql = QString("select a.* from fslayer a where a.fsapp = '%1'").arg(item);

        rd = m_SqLPara->RecordSet(sql.toStdString());
        items.clear();
        if(rd.size()>0){
            for(RECORDSET::iterator it = rd.begin();it!=rd.end();it++){
            //for(int i = 0;i<rd.size();i++){
                nd =  *it;
                value = nd["para"];
                if(value ==""){
                    //QMessageBox box(QMessageBox::Warning,"警告","图层无测量点,请添加测量！");
                    //box.setStandardButtons (QMessageBox::Ok|QMessageBox::Cancel);
                    //box.setStandardButtons (QMessageBox::Ok);
                    //box.setButtonText (QMessageBox::Ok,QString("确 定"));
                    //box.setButtonText (QMessageBox::Cancel,QString("取 消"));
                    //box.exec();
                    MSGINF::MsgShowOk(this,_("Warning"),_("Project Layer Measure Is None,Add Measure Please."));
                    return;
                }
                vlayer = nd["value"];
                layers << QString::fromLocal8Bit(vlayer.c_str());
                items << QString::fromLocal8Bit(value.c_str());
                qDebug()<< vlayer.c_str() << value.c_str();
            }
        }
        else{
            //QMessageBox box(QMessageBox::Warning,"警告","工程没有图层,请添加图层！");
            //box.setStandardButtons (QMessageBox::Ok|QMessageBox::Cancel);
            //box.setStandardButtons (QMessageBox::Ok);
            //box.setButtonText (QMessageBox::Ok,QString("确 定"));
            //box.setButtonText (QMessageBox::Cancel,QString("取 消"));
            //box.exec();
            MSGINF::MsgShowOk(this,_("Warning"),_("Project Layer Is None,Add Layer Please."));
            return;
        }

        m_OpenProjectName = item;
        dock1->setWindowTitle(_("Project")+ ":" + m_OpenProjectName);



        //openJson(strJson);

        headL << _("Measure")<<_("Gap")<<_("FLush")<<_("State");
        m_RunTable->clear();
        m_RunTable->setRowCount(0);
        m_RunTable->setColumnCount(4);
        m_RunTable->setHorizontalHeaderLabels(headL);
        //m_RunTable->setSelectionMode(QAbstractItemView::SingleSelection);
        m_RunTable->setSelectionBehavior(QAbstractItemView::SelectRows);
        for(int i=0;i<items.size();i++)
            addItem(items.at(i),layers.at(i));

        m_box->RefresItem();
        m_box->OnSetEnable(true);
    }

}

bool MainWindow::showRunTableAuto(QString Prj)
{
    QStringList headL;
    //headL << "Label"<<"GapNom"<<"Gap+"<<"Gap-"<<"FlushNum"<<"Gap"<<"FLush"<<"ICON";

    bool ok = false;
    QString sql;
    QStringList items,layers;
    NODE nd;
    NODE rds;
    std::string value,vlayer;;
    items << tr("Spring") << tr("Summer") << tr("Fall") << tr("Winter");
    items.clear();
    layers.clear();

    sql = QString("select * from fsapp where value = '%1'").arg(Prj);
    RECORDSET rd = m_SqLPara->RecordSet(sql.toStdString());

    if(rd.size()<=0){
        qDebug() << "project " << Prj << "Not exist.";
        return false;
    }

    sql = QString("select a.* from fslayer a where a.fsapp = '%1'").arg(Prj);

    rd = m_SqLPara->RecordSet(sql.toStdString());
    items.clear();
    if(rd.size()>0){
        for(RECORDSET::iterator it = rd.begin();it!=rd.end();it++){
        //for(int i = 0;i<rd.size();i++){
            nd =  *it;
            value = nd["para"];
            if(value ==""){
                //MSGINF::MsgShowOk(this,_("Warning"),_("Project Layer Measure Is None,Add Measure Please."));
                qDebug() << "Project Layer Measure Is None,Add Measure Please.";
                return false;
            }
            vlayer = nd["value"];
            layers << QString::fromLocal8Bit(vlayer.c_str());
            items << QString::fromLocal8Bit(value.c_str());
            qDebug()<< vlayer.c_str() << value.c_str();
        }
    }
    else{
        //MSGINF::MsgShowOk(this,_("Warning"),_("Project Layer Is None,Add Layer Please."));
        qDebug() << "Project Layer Is None,Add Layer Please.";
        return false;
    }

    m_OpenProjectName = Prj;
    dock1->setWindowTitle(_("Project")+ ":" + m_OpenProjectName);



    //openJson(strJson);

    headL << _("Measure")<<_("Gap")<<_("FLush")<<_("State");
    m_RunTable->clear();
    m_RunTable->setRowCount(0);
    m_RunTable->setColumnCount(4);
    m_RunTable->setHorizontalHeaderLabels(headL);
    //m_RunTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_RunTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    for(int i=0;i<items.size();i++)
        addItem(items.at(i),layers.at(i));

    m_box->RefresItem();
    return true;
}

void MainWindow::addItem(QString str,QString layer)
{

    /*
    circlePath.addRect(QRect(0, 0, 400, 300));

    squarePath.addRect(QRect(0, 0, 160, 60));
    squarePath.moveTo(0 ,30);
    squarePath.lineTo(160, 30);s
    squarePath.moveTo(80 ,30);
    squarePath.lineTo(80, 60);
    */
    int tp,cnt=0,rowC;
    neb::CJsonObject cjs,ndcjs;
    std::string  stdPic="",pin;
    if(cjs.Parse(str.toStdString())){
        for(int i=0;i<cjs["shape"].GetArraySize();i++){
            ndcjs.Clear();
            cjs["shape"].Get(i,ndcjs);
            ndcjs.Get("type",tp);
            if(tp == E_BITMAP){
                stdPic.append(ndcjs.ToString());
                stdPic.append(";");
                qDebug()<<stdPic.c_str();
                cnt++;
            }

        }
        rowC = m_RunTable->rowCount();
        m_RunTable->setRowCount(rowC+cjs["shape"].GetArraySize()-cnt);
        qDebug()<<"rowC = "<<rowC << m_RunTable->rowCount();

        cnt=0;

        for(int i=0;i<cjs["shape"].GetArraySize();i++){
            ndcjs.Clear();
            cjs["shape"].Get(i,ndcjs);
            ndcjs.Get("type",tp);
            if(tp == E_NORMAL){
                qDebug()<<ndcjs.ToString().c_str();
                pin="";
                ndcjs.Get("point",pin);
                QTableWidgetItem* item = new QTableWidgetItem(pin.c_str(), 0);
                //item->setFlags(Qt::ItemIsEditable);
                item->setFlags(item->flags() & (~Qt::ItemIsEditable));
                item->setWhatsThis(stdPic.c_str());

                m_RunTable->setItem(cnt+rowC,0,item);

                for(int col=1;col<3;col++){
                    QTableWidgetItem* item1 =new QTableWidgetItem("", 0);
                    item1->setFlags(item1->flags() & (~Qt::ItemIsEditable));
                    //
                    if(col==1)
                        item1->setWhatsThis(ndcjs.ToString().c_str());
                    if(col==2)
                        item1->setWhatsThis(layer);

                    m_RunTable->setItem(cnt+rowC,col,item1);
                }
                QLabel *label = new QLabel();
                label->setPixmap(QPixmap(":/images/Selection.png"));
                label->setAlignment(Qt::AlignHCenter);
                m_RunTable->setCellWidget(cnt+rowC,3,label);

                //((QLabel*)m_RunTable->cellWidget(i,3))->setPixmap(QPixmap(":/images/Apply.png"));
                m_RunTable->setRowHeight(cnt+rowC, 33);
                m_RunTable->setColumnWidth(3,40);
                //QTableWidgetItem* item2 =new QTableWidgetItem(QIcon(":/images/Selection.png"),"", 0);
                //item2->setFlags(item2->flags() & (~Qt::ItemIsEditable));
                //m_RunTable->setItem(i,3,item2);

                //
                cnt++;
            }

        }

    }



}

void MainWindow::onConnectCamera()
{
    qDebug()<<__FUNCTION__;
}
void MainWindow::onConnectMIS()
{
    qDebug()<<__FUNCTION__;
    QString app = m_OpenProjectName;
    QString buf;
    //std::string chkstart;
    buf = QString("%1,switch\r\n$FEXA").arg(app);
    //m_SqLPara->GetValue("MIS-Start",chkstart);
    //if(chkstart=="1"){
        qDebug()<< "Send MIS:" << buf.toLocal8Bit();
        m_TcpMIS->write(buf.toLocal8Bit(),buf.length());
    //}

}
void MainWindow::onConnectRobot()
{
    qDebug()<<"robot connected";
}
void MainWindow::onDisconnectCamera()
{
    qDebug()<<__FUNCTION__;
}
void MainWindow::onDisconnectMIS()
{
    qDebug()<<__FUNCTION__ << m_MisConReplayCnt;
    if(m_MisConReplayCnt>0){
        //qDebug() << "MIS replay Connect " << 4-m_MisConReplayCnt;
        QTimer::singleShot(5000,this,SLOT(OnMISReplay()));
    }
}
void MainWindow::onDisconnectRobot()
{
    qDebug()<<__FUNCTION__;
}

void MainWindow::onReadyReadCamera()
{
    //qDebug()<<__FUNCTION__;
    QByteArray buffer=m_TcpCamera->readAll();
    QString str = buffer.data();
    if(!buffer.isEmpty())
    {
        qDebug()<<str;
        QStringList list1 = str.split('#',QString::SkipEmptyParts);
        for(int i=0;i<list1.size();i++){
            QStringList list2 = list1.at(i).split(',');
            if(list2.size()<2){
                qDebug()<<"Receive Camera data error." << list1.at(i);
            }
            else{
                QList<QTableWidgetItem *> items;
                //bool b ;
                items = m_RunTable->findItems(list2.at(2),Qt::MatchExactly);
                //b = items.isEmpty();
                if(items.size()>0){
                    int row = items.at(0)->row();
                    if(row == m_RunTable->currentRow()){
                        RunitemSelectionChanged();
                    }
                    if(list2.at(1) != m_OpenProjectName){
                        qWarning() << "Project Name " << list2.at(1) << " != " << m_OpenProjectName;
                    }
                    //qDebug()<<row;
                    int flag = showItem(row,list2);
                    m_RunTable->setCurrentCell(row,0);


                    if(list2.at(0) == "anserr"){
                        emit showGapFlush(list2.at(2),"-0","-0",0);

                        QString buf;
                        std::string chkstart;
                        QString dt,tim;
                        QDateTime time = QDateTime::currentDateTime();
                        dt = time.toString("yyyyMMdd");
                        tim = time.toString("hhmmss");
                        buf = QString("%1,%2,%3,-0,-0,%4,%5,-0\r\n$FEXA").arg(m_OpenProjectName,m_clsid,list2.at(2),dt,tim);
                        m_SqLPara->GetValue("MIS-Start",chkstart);
                        if(chkstart=="1"){
                            qDebug()<< "Send MIS:" << buf.toLocal8Bit();
                            m_TcpMIS->write(buf.toLocal8Bit(),buf.length());
                        }

                    }
                    else if(list2.at(0) == "ans"){
                        emit showGapFlush(list2.at(2),list2.at(3),list2.at(4),flag);
                        //save data
                        m_clsid = m_ModeTxt->text();
                        m_clsid = m_clsid.trimmed();
                        onSaveData(list2.at(2),list2.at(3),list2.at(4),flag);
                    }
                    else
                        qDebug()<<"Error CMD!! " << str;
                }
                else{
                    qDebug()<<"No Match Measure!!! " << list2.at(1);
                }
            }
            //qDebug()<<list1.at(i);
        }
        if(m_TcpRobot->state() == QAbstractSocket::ConnectedState){
            m_TcpRobot->write("OK\r");
        }
    }
}

int MainWindow::showItem(int row,QStringList ls)
{
    int ret = 0;;
    if(ls.size()<4){
        m_RunTable->item(row,1)->setText("-0");
        m_RunTable->item(row,2)->setText("-0");
    }
    else {
        m_RunTable->item(row,1)->setText(ls.at(3));
        m_RunTable->item(row,2)->setText(ls.at(4));
    }
    QLabel* lb = (QLabel*)m_RunTable->cellWidget(row,3);



    if(ls.at(0) == "anserr"){
        lb->setPixmap(QPixmap(":/images/1F6A8.png"));
        return 0;
    }


    ret = getGapFlushFlag(ls.at(2),ls.at(3),ls.at(4));



    if(ret==0x0101)
        lb->setPixmap(QPixmap(":/images/Apply.png"));
    //:/images/Apply.png
    else if(ret>0)
        lb->setPixmap(QPixmap(":/images/Cancel.png"));
    else//never run this..
        lb->setPixmap(QPixmap(":/images/1F514.png"));

    return ret;
}

int MainWindow::getGapFlushFlag(QString Measure,QString sgap,QString sflush)
{
    int ret = 0;
    QString sql,gap,gapmin,gapmax,flush,flushmin,flushmax;
    float fgap,fgapmin,fgapmax,fflush,fflushmin,fflushmax,ffgap,ffflush;

    ffgap =qAbs(sgap.toFloat());
    ffflush = qAbs(sflush.toFloat());

    NODE nd;
    NODE rds;
    std::string value;
    sql = QString("select * from fspoint where id = '%1' and fsapp = '%2'").arg(Measure,m_OpenProjectName);

    RECORDSET rd = m_SqLPara->RecordSet(sql.toStdString());

    if(rd.size()>0){
        //for(RECORDSET::iterator it = rd.begin();it!=rd.end();it++)

            nd =  *rd.begin();
            gap = nd["gap"].c_str();
            gapmin = nd["gapmin"].c_str();
            gapmax = nd["gapmax"].c_str();
            flush = nd["flush"].c_str();
            flushmin = nd["flushmin"].c_str();
            flushmax = nd["flushmax"].c_str();

            fgap = gap.toFloat();
            fgapmin = gapmin.toFloat();
            fgapmax = gapmax.toFloat();
            fflush = fabsf(flush.toFloat());
            fflushmin = flushmin.toFloat();
            fflushmax = flushmax.toFloat();

            qDebug() << "gapmin:" << gapmin << "flushmin:" << flushmin;
            qDebug() << "gapmax:" << gapmax << "flushmax:" << flushmax;
            qDebug() << "ffgap:" << ffgap << "ffflush:" << ffflush;
            //green
            if((fgap-fgapmin) <= ffgap  && ffgap <=(fgap+fgapmax)){
                ret = 1;
            }
             ret <<=8;
            //green
            if(((fflush-fflushmin)<=ffflush)  && (ffflush<=(fflush+fflushmax))){

                ret |= 1;
            }
            //red two common value.
            int gapvalue2,flushvalue2;
            gapvalue2 = 2*(fgapmax+fgapmin);
            flushvalue2 = 2*(fflushmax+fflushmin);

            //qDebug() << "gapvalue2:" << gapvalue2 << "flushvalue2:" << flushvalue2;

            if(qAbs(ffgap-fgap)>gapvalue2){
                ret|=0x200;
                ret&=0xF2FF;
            }

            if(qAbs(ffflush-fflush)>flushvalue2){
                ret|=0x02;
                ret&=0xFFF2;
            }
            //Nothing value
            if(sgap == "-"){
                ret &=0x01FF;
                ret |=0x0100;
            }
            if(sflush == "-"){
                ret &=0xff01;
                ret |=0x0001;
            }

    }
    else
        ret = -1;

    return ret;
}
void MainWindow::onReadyReadRobot()
{

    QByteArray buffer=m_TcpRobot->readAll();
    QString str = buffer.data();
    QString measure;
    if(!buffer.isEmpty())
    {
        qDebug()<<buffer;
        QStringList list1 = str.split('#',QString::SkipEmptyParts);
        measure = list1.at(0);
        //for(int i=0;i<list1.size();i++)
        {
            QStringList list2 = list1.at(0).split(',',QString::SkipEmptyParts);
            if(list2.size()==2){
                if(m_OpenProjectName != list2.at(0)){
                    if(showRunTableAuto(list2.at(0))==false){
                        return;
                    }
                }
                measure = list2.at(1);
            }

            str = QString("act,%1,%2#").arg(m_OpenProjectName,measure);
            qDebug()<<str;
            if(m_TcpCamera->state() == QAbstractSocket::ConnectedState )
                m_TcpCamera->write(str.toLocal8Bit());

        }

    }

}
void MainWindow::onReadyReadMIS()
{

    QByteArray buffer=m_TcpMIS->readAll();
    QString str = buffer.data();
    if(!buffer.isEmpty())
    {
        qDebug()<<buffer;
    }

}
void MainWindow::displayError(QAbstractSocket::SocketError e)
{
    //((QTcpSocket*)sender())->disconnectFromHost();
    //qDebug()<<"socket error: "<<e;
    qDebug()<<sender()->objectName()<<":" << ((QTcpSocket*)sender())->errorString();

}

void MainWindow::RuncellChanged(int row,int col)
{
    //qDebug()<<m_RunTable->item(row,col)->whatsThis();
}
void MainWindow::RunitemChanged(QTableWidgetItem* item)
{
    //qDebug()<<"1111111111111111";
}

void MainWindow::RunitemSelectionChanged()
{

    int row = m_RunTable->currentRow();
    if(row<0) return;

    QString strPic=m_RunTable->item(row,0)->whatsThis();
    QString strPin = m_RunTable->item(row,1)->whatsThis();

    //layer
    QString layer = m_RunTable->item(row,2)->whatsThis();

    QString measure,gap,flush;
    int flag;
    measure = m_RunTable->item(row,0)->text();
    gap = m_RunTable->item(row,1)->text() == "" ? "-":m_RunTable->item(row,1)->text();
    flush = m_RunTable->item(row,2)->text()=="" ? "-":m_RunTable->item(row,2)->text();


    //m_RunTable->item(row,0)->whatsThis();
    emit boxShowPin(strPic,strPin);
    flag = getGapFlushFlag(measure,gap,flush);

    emit showGapFlush(measure,gap,flush,flag);
    //qDebug()<<row << strPic.toStdString().c_str() << strPin.toStdString().c_str();

    //set title
    QString title = QString("%1:%2 %3:%4").arg(_("Project"),m_OpenProjectName,_("Layer"),layer);
    dock2->setWindowTitle(title);

}

void MainWindow::onSaveData(QString point,QString gap,QString flush,int flag)
{
    QString app = m_OpenProjectName;//dock1->windowTitle();
    QString sql = QString("insert into fsdata ('classid','point','fsapp') values('%1','%2','%3')").arg(m_clsid,point,app);
    QString dt,tim;
    QDateTime time = QDateTime::currentDateTime();
    dt = time.toString("yyyyMMdd");
    tim = time.toString("hhmmss");
    QString sqlu = QString("update fsdata set 'gap'='%1','flush'='%2','state'='%3','dt'='%4','tim'='%5' where classid='%6' and point='%7' and fsapp='%8'")
            .arg(gap,flush).arg(flag,0,10).arg(dt,tim,m_clsid,point,app);

    m_SqLPara->exeSql(sql.toStdString());
    m_SqLPara->exeSql(sqlu.toStdString());
    qDebug()<< sql;
    qDebug()<< sqlu;
    //
    QString buf;
    std::string chkstart;
    buf = QString("%1,%2,%3,%4,%5,%6,%7,%8\r\n$FEXA").arg(app,m_clsid,point,gap,flush).arg(flag,0,10).arg(dt,tim);
    m_SqLPara->GetValue("MIS-Start",chkstart);
    if(chkstart=="1"){
        qDebug()<< "Send MIS:" << buf.toLocal8Bit();
        m_TcpMIS->write(buf.toLocal8Bit(),buf.length());
    }
}
void MainWindow::closeEvent(QCloseEvent *event)
{
    switch( QMessageBox::information(
                this, _("AlsonVision"),
                _("Are you sure Quit?"),
                _("Yes"),
                _("No"),
                0, 1 ) )
    {
     case 0:
     event->accept();
        break;
     case 1:
     default:
        event->ignore();
        break;
    }
}
void MainWindow::myHelp()
{
    qDebug() << __FUNCTION__;
}
void MainWindow::myAbout()
{
    qDebug() << __FUNCTION__;
    QString sAbout = " ALSON-AutoGFM.\r\n Copyright 2023 \t\r\n 1.0.0";
    //sAbout.append(COPYRIGHT);
    //MSGINF::MsgAbout(this,_("About"),sAbout);

    QMessageBox box(QMessageBox::Question,tr("关于"),sAbout,
                    QMessageBox::Ok,this);
    //box.setStandardButtons (QMessageBox::Ok|QMessageBox::Cancel);
    QPixmap bmp = QPixmap(":/fsapp.ico");
    QPixmap pix = bmp.scaled(64,64);
    //box.setIconPixmap(QPixmap(":/fsapp.ico"));
    box.setButtonText (QMessageBox::Ok,tr("Ok"));
    box.exec();

}
void MainWindow::myExport()
{
    ExportDialog *dlg= new ExportDialog(m_SqLPara);
    Qt::WindowFlags flags = Qt::Dialog;
    flags |= Qt::WindowCloseButtonHint;
    dlg->setWindowFlags(flags);
    dlg->exec();
}
void MainWindow::myImport()
{
    ImportDialog *dlg= new ImportDialog(m_SqLPara);
    Qt::WindowFlags flags = Qt::Dialog;
    flags |= Qt::WindowCloseButtonHint;
    dlg->setWindowFlags(flags);
    dlg->exec();
}
void MainWindow::OnClearRunTable()
{

    int rowNum=  m_RunTable->rowCount();
    for(int i = 0 ; i < rowNum ; i++)//清空列表
    {
        m_RunTable->removeRow(0);
    }
    dock1->setWindowTitle(_("Project:none"));
    m_ModeTxt->setText("");
}

void MainWindow::OnShowHideDock1(bool bf)
{
    if(bf)
        dock1->show();
    else
        dock1->hide();
}

void MainWindow::OnMISReplay()
{

    qDebug() << "MIS replay Connect " << m_MisConReplayCnt;
    BOOL  bDontLinger = FALSE;
    if(m_MisConReplayCnt>0){
        m_MisConReplayCnt--;
        std::string IP1,IP3,Port5;
        int iPort5;
        m_SqLPara->GetValue("LocalIP",IP1);
        m_SqLPara->GetValue("MIS-IP",IP3);
        m_SqLPara->GetValue("MIS-Port",Port5);
        iPort5 = std::stoi(Port5);

            m_TcpMIS->SetLocalPort(QString(IP1.c_str()),(quint16)8989);
            m_TcpMIS->connectToHost(QString(IP3.c_str()),(quint16)iPort5,QAbstractSocket::ReadWrite,QAbstractSocket::IPv4Protocol);
            if(!m_TcpMIS->waitForConnected(5000))
            {
              qDebug() << "Error: " << m_TcpMIS->errorString();
              //((QToolButton*)sender())->setChecked(false);
              QTimer::singleShot(5000,this,SLOT(OnMISReplay()));
              return;
            }
            setsockopt(m_TcpMIS->socketDescriptor(),SOL_SOCKET,SO_DONTLINGER,(const char*)&bDontLinger,sizeof(BOOL));
            m_MisConReplayCnt=3;
    }
}
